package org.zuel.boot.demo.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.zuel.boot.demo.web.*;
import org.zuel.boot.demo.exception.ParameterException;
import org.zuel.boot.demo.entity.SysUser;
import org.zuel.boot.demo.mapper.SysUserMapper;
import org.zuel.boot.demo.service.ISysUserService;
import org.springframework.stereotype.Service;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.Objects;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;


/**
 *  服务实现类
 *
 * @author ikun
 */
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements ISysUserService {


    @Override
    public PageResult<SysUser> list(PageParam<SysUser> page) {
        return new PageResult<>(this.page(page).getRecords(), page.getTotal());
    }

    @Override
    public JsonResult read(Integer id) {
        if (id == null) {
            throw new ParameterException("参数对象为空");
        }

        SysUser sysUser = baseMapper.selectById(id);
        return JsonResult.ok().setData(sysUser);
    }

    @Override
    public JsonResult add(SysUser sysUser) {
        if (sysUser ==null){
            throw new ParameterException("参数对象为空");
        }

        baseMapper.insert(sysUser);
        return JsonResult.ok("添加成功");
    }

    @Override
    public JsonResult update(SysUser sysUser) {
        if (sysUser == null) {
            throw new ParameterException("参数对象为空");
        }

        if (sysUser.getUserId() == null) {
            throw new ParameterException("参数对象id为空");
        }

        baseMapper.updateById(sysUser);
        return JsonResult.ok("修改成功");
    }

    @Override
    public JsonResult delete(Integer[] ids) {
        if (ids == null) {
            throw new ParameterException("参数对象为空");
        }

        if (ids != null || ids.length > 0) {
            baseMapper.deleteBatchIds(Arrays.asList(ids));
        }
        return JsonResult.ok("删除成功");
    }

    private static final ConcurrentHashMap<String, SysUser> sessionMap = new ConcurrentHashMap<>();

    @Override
    public JsonResult login(SysUser sysUser) {
        try {
            // 查询用户
            SysUser user = baseMapper.selectOne(new QueryWrapper<SysUser>().eq("username", sysUser.getUsername()));

            // 验证用户是否存在
            if (user == null) {
                return JsonResult.error("用户不存在");
            }

            // 验证密码是否正确
            if (!user.getPassword().equals(sysUser.getPassword())) {
                return JsonResult.error("密码错误");
            }

            // 登录成功，生成新的Session ID
            String sessionId = UUID.randomUUID().toString();
            user.setSessionId(sessionId); // 将sessionId存储在用户对象中
            baseMapper.updateById(user);
            sessionMap.put(sessionId, user);

            // 设置Cookie
            HttpServletResponse response = ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getResponse();
            Cookie cookie = new Cookie("sessionId", sessionId);
            cookie.setMaxAge(60 * 60 * 24 * 7); // 设置Cookie有效期为7天
            cookie.setPath("/");
            cookie.setHttpOnly(true); // 防止XSS攻击
            if (response != null) {
                response.addCookie(cookie);
            }
            return JsonResult.ok("登录成功").setData(user.getUserType());
        } catch (Exception e) {
            return JsonResult.error("系统错误，请稍后再试");
        }
    }

    public SysUser getSessionUser(String sessionId) {
        return sessionMap.get(sessionId);
    }
}